#include <cstdlib>
#include <algorithm>
#include <fstream>
#include <string>
#include <unordered_map>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include "parse_info.h"

// 所有支持的配置项
const std::vector<ConfigOption> ALL_CONFIG_OPTIONS = {
    {ConfigKey::PORT, "-p", "--port", "服务器监听端口", "<int>"},
    {ConfigKey::BUFFER_SIZE, "-bs", "--buffer-size", "缓冲区大小", "<int>"},
    {ConfigKey::BACKLOG, "-b", "--backlog", "连接队列长度", "<int>"},
    {ConfigKey::MAX_EVENTS, "-me", "--max-events", "epoll最大事件数", "<int>"},
    {ConfigKey::EPOLL_TIMEOUT, "-et", "--epoll-timeout", "epoll超时时间(ms)", "<int>"},
    {ConfigKey::THREAD_POOL_SIZE, "-ts", "--thread-pool-size", "线程池大小", "<int>"},
    {ConfigKey::HEARTBEAT_INTERVAL, "-hi", "--heartbeat-interval", "心跳检测间隔(秒)", "<int>"},
    {ConfigKey::CONNECTION_TIMEOUT, "-ct", "--connection-timeout", "连接超时时间(秒)", "<int>"}};

// 帮助信息
void print_help() {
    std::cout << "用法: server [选项]...\n\n";
    std::cout << "选项:\n";

    for (const auto &opt : ALL_CONFIG_OPTIONS) {
        std::cout << "  " << std::left << std::setw(5) << opt.short_name << ", " << std::setw(20)
                  << opt.long_name << " " << std::setw(10) << opt.value_type << " "
                  << opt.description << "\n";
    }

    std::cout << "  " << std::left << std::setw(5) << "-h"
              << ", " << std::setw(20) << "--help"
              << " " << std::setw(10) << ""
              << " 显示帮助信息\n";

    std::cout << "  " << std::left << std::setw(5) << "-c"
              << ", " << std::setw(20) << "--config"
              << " " << std::setw(10) << "<file>"
              << " 从配置文件加载设置\n";
}
// 将字符串转换为ConfigKey
ConfigKey string_to_config_key(const std::string &key) {
    static const std::unordered_map<std::string, ConfigKey> key_map = {
        {"port", ConfigKey::PORT},
        {"buffer_size", ConfigKey::BUFFER_SIZE},
        {"backlog", ConfigKey::BACKLOG},
        {"max_events", ConfigKey::MAX_EVENTS},
        {"epoll_timeout", ConfigKey::EPOLL_TIMEOUT},
        {"thread_pool_size", ConfigKey::THREAD_POOL_SIZE},
        {"heartbeat_interval", ConfigKey::HEARTBEAT_INTERVAL},
        {"connection_timeout", ConfigKey::CONNECTION_TIMEOUT}};

    auto it = key_map.find(key);
    if (it != key_map.end()) {
        return it->second;
    }
    throw std::invalid_argument("Unknown config key: " + key);
}

// 解析配置文件
std::unordered_map<ConfigKey, int> parse_config_file(const std::string &filename) {
    std::unordered_map<ConfigKey, int> config;
    std::ifstream file(filename);

    if (!file.is_open()) {
        std::cerr << "无法打开配置文件: " << filename << std::endl;
        return config;
    }

    std::string line;
    while (std::getline(file, line)) {
        // 跳过注释和空行
        if (line.empty() || line[0] == '#') continue;

        size_t pos = line.find('=');
        if (pos != std::string::npos) {
            std::string key_str   = line.substr(0, pos);
            std::string value_str = line.substr(pos + 1);

            // 去除前后空格
            key_str.erase(0, key_str.find_first_not_of(" \t"));
            key_str.erase(key_str.find_last_not_of(" \t") + 1);
            value_str.erase(0, value_str.find_first_not_of(" \t"));
            value_str.erase(value_str.find_last_not_of(" \t") + 1);

            try {
                ConfigKey key = string_to_config_key(key_str);
                int value     = std::stoi(value_str);
                config[key]   = value;
            } catch (const std::exception &e) {
                std::cerr << "配置文件解析错误: " << e.what() << " (行: " << line << ")"
                          << std::endl;
            }
        }
    }

    return config;
}

void show_config_info(std::unordered_map<ConfigKey, int> &config) {
    // 使用配置
    std::cout << "服务器配置:\n";
    for (const auto &[key, value] : config) {
        for (const auto &opt : ALL_CONFIG_OPTIONS) {
            if (opt.key == key) {
                std::cout << "  " << std::left << std::setw(20) << opt.long_name << ": " << value
                          << "\n";
                break;
            }
        }
    }
}

// 解析命令行参数
void parse_command_line(int argc, char *argv[], std::unordered_map<ConfigKey, int> &config) {
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        // 处理帮助选项
        if (arg == "-h" || arg == "--help") {
            print_help();
            exit(EXIT_SUCCESS);
        }

        // 处理配置文件选项
        if (arg == "-c" || arg == "--config") {
            if (i + 1 < argc) {
                auto file_config = parse_config_file(argv[i + 1]);
                // 合并配置，但不覆盖已存在的值
                for (const auto &[key, value] : file_config) {
                    if (config.find(key) != config.end()) {
                        config[key] = value;
                    }
                }
                i++;
            }
            continue;
        }

        // 处理其他配置选项
        bool option_found = false;
        for (const auto &opt : ALL_CONFIG_OPTIONS) {
            if (arg == opt.short_name || arg == opt.long_name) {
                if (i + 1 < argc) {
                    try {
                        config[opt.key] = std::stoi(argv[i + 1]);
                        i++;
                        option_found = true;
                        break;
                    } catch (const std::exception &e) {
                        std::cerr << "错误: 无效的参数值 '" << argv[i + 1] << "' 对于选项 " << arg
                                  << "\n";
                        exit(EXIT_FAILURE);
                    }
                } else {
                    std::cerr << "错误: 选项 " << arg << " 需要一个参数\n";
                    exit(EXIT_FAILURE);
                }
            }
        }

        if (!option_found) {
            std::cerr << "错误: 未知选项 " << arg << "\n";
            print_help();
            exit(EXIT_FAILURE);
        }
    }
}